const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/

const colorRgb = function () {
  var sColor = this.toLowerCase()

  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'

      for (var i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    var sColorChange = []

    for (var i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    return 'RGB(' + sColorChange.join(',') + ')'
  } else {
    return sColor
  }
}

const colorOpacityRgba = function (color, opacity) {
  var sColor = color.toLowerCase()

  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'

      for (var i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    var sColorChange = []

    for (var i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    sColorChange.push(parseFloat(opacity))
    return 'RGB(' + sColorChange.join(',') + ')'
  } else {
    return sColor
  }
}

/**
 *
 * @param hex 例如:"#23ff45"
 * @param opacity 透明度
 * @returns {string}
 */
const hexToRgba = (hex, opacity) => {
  return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')'
}

export { colorRgb, colorOpacityRgba, hexToRgba }
